package cn.lingyangwl.agile.infra.weixin.mp.assembly;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.lingyangwl.agile.model.BaseAssembly;
import cn.lingyangwl.agile.model.enums.BoolEnum;
import cn.lingyangwl.agile.model.module.config.param.WxMpParam;
import cn.lingyangwl.agile.infra.weixin.mp.model.entity.MpUser;
import cn.lingyangwl.agile.infra.weixin.mp.model.rqrs.MpUserResp;
import cn.lingyangwl.agile.infra.weixin.mp.model.rqrs.MpUserUpdateReq;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 公众号粉丝
 *
 * @author shenguangyang
 */
@Mapper(componentModel = "spring")
public interface MpUserAssembly extends BaseAssembly {
    MpUserResp toMpUserRS(MpUser source);

    @Mappings({
            @Mapping(source = "mpAppId", target = "mpAppId"),
            @Mapping(source = "wxMpUser.openId", target = "openId"),
            @Mapping(source = "wxMpUser.subscribe", target = "subscribeStatus", qualifiedByName = BOOL_TO_STR),
            @Mapping(source = "wxMpUser.nickname", target = "nickname"),
            @Mapping(source = "wxMpUser.headImgUrl", target = "headImageUrl"),
            @Mapping(source = "wxMpUser.remark", target = "remark"),
            @Mapping(source = "wxMpUser.subscribeTime", target = "subscribeTime", qualifiedByName = LONG_TO_DATE),
            @Mapping(source = "wxMpUser.language", target = "language"),
            @Mapping(source = "wxMpUser.tagIds", target = "tagIds", qualifiedByName = ARRAY_TO_LIST),
    })
    MpUser toMpUser(String mpAppId, WxMpUser wxMpUser);

    default MpUser toMpUser(WxMpParam param, WxMpUser wxMpUser) {
        MpUser user = toMpUser(param.getAppId(), wxMpUser);
        user.setSubscribeStatus(wxMpUser.getSubscribe() ? BoolEnum.TRUE.getCode() : BoolEnum.FALSE.getCode());
        user.setSubscribeTime(DateUtil.date(LocalDateTimeUtil.of(wxMpUser.getSubscribeTime() * 1000L)));
        user.setMpAppId(param.getAppId());
        return user;
    }

    default List<MpUser> toMpUserList(WxMpParam param, List<WxMpUser> wxUsers) {
        return wxUsers.stream().map(e -> toMpUser(param, e)).collect(Collectors.toList());
    }

    MpUser toMpUser(MpUserUpdateReq source);
}
